import express from "express";
import jwt from "jsonwebtoken";
import bodyParser from 'body-parser'
import menu from "./menu.js";

// 定义加密字符串
const secret = "secretToken";
const port = 8765;
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
let token = ''

app.all("*",function(req, res, next){
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
  res.header("Access-Control-Allow-Headers", "Content-Type,access-token,Authorization"); 
  res.header("Access-Control-Allow-Credentials", "true");
  next()
})

// 获取token
app.post("/getToken", (req, res) => {
  let { data } = req.body;
  if(!['admin', '张三'].includes(data.account)) {
    res.send({
      status: 403,
      message: 'There is no such user!',
      data: []
    });
  } else {
    // 生成token
    token = jwt.sign(data, secret);
    // 前端传过来的数据
    setTimeout(() => {
      res.send({
        token
      });
    }, 500);
  }
});

// 获取菜单
app.post("/getMenu", (req, res) => {
  let { data } = req.body;
  if(token !== req.headers.authorization) {
    res.send({
      status: 200,
      message: 'token失效',
      data: []
    });
    return
  }
  
  setTimeout(() => {
    // 解密token
    let decoded = jwt.verify(token, secret);
    if(decoded.account === 'admin') {
      if(data.lang === 'en') {
        res.send({
          data: menu.admin.en
        });
      } else {
        res.send({
          data: menu.admin.zhCn
        });
      }
    } else if(decoded.account === '张三') {
      if(data.lang === 'en') {
        res.send({
          data: menu.user.en
        });
      } else {
        res.send({
          data: menu.user.zhCn
        });
      }
    } else {
      if(data.lang === 'en') {
        res.send({
          status: 403,
          message: 'There is no such user!',
          data: []
        });
      }
    }
  }, 300);
});

// 获取所有用户
app.post("/getAllUser", (req, res) => {
  setTimeout(() => {
    res.send({
      status: 200,
      message: '成功',
      data: []
    });
  }, 500);
});


app.listen(port, () => {
  console.log(`端口${ port }运行中....`);
});
